package com.xcc.shopanim.adapter;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.xcc.shopanim.BaseFragment;

import java.util.List;

/**
 * ****************************************************
 * 作者 :: rookieCi<1056907550@qq.com>
 * ----------------------------------------------------
 * git :: https://gitee.com/rookieci
 * ----------------------------------------------------
 * 博客 :: http://blog.csdn.net/xcccicishuai
 * ----------------------------------------------------
 * 时间 :: 2019/6/19 Add by rookieCi
 * ----------------------------------------------------
 * 描述 :: ViewPagerAdapter
 * ****************************************************
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private List<BaseFragment> fragmentList;
    private String titles[];
    private BaseFragment.OnFragmentCallBack onFragmentCallBack;

    public ViewPagerAdapter setOnFragmentCallBack(BaseFragment.OnFragmentCallBack onFragmentCallBack) {
        this.onFragmentCallBack = onFragmentCallBack;
        return this;
    }

    public ViewPagerAdapter setTitles(String[] titles) {
        this.titles = titles;
        return this;
    }

    public ViewPagerAdapter(FragmentManager fm, List<BaseFragment> fragmentList) {
        super(fm);
        this.fragmentList = fragmentList;
    }

    public Fragment getItem(int position) {
        return fragmentList.get(position).setOnFragmentCallBack(onFragmentCallBack);
    }

    public int getCount() {
        return fragmentList != null ? fragmentList.size() : 0;
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        for (int i = 0; i < fragmentList.size(); i++) {
            BaseFragment fragment = fragmentList.get(i);
            if (object == fragment) {
                return POSITION_UNCHANGED;
            }
        }
        destroyItem(null, 0, object);
        return POSITION_NONE;
    }

    public CharSequence getPageTitle(int position) {
        if (titles != null && titles.length > 0) {
            return titles[position % titles.length];
        } else return super.getPageTitle(position);
    }
}